package org.monte.previo2.servicios;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.monte.previo2.MainActivity;
import org.monte.previo2.R;

import org.monte.previo2.base.ManagerDB;
import org.monte.previo2.clases.Imagen;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

import android.os.Vibrator;
import android.widget.RemoteViews;
import android.widget.Toast;

public class Sincronizar extends IntentService{
	final static private String APP_KEY = "gn6mw3jxqv771rv";
	final static private String APP_SECRET = "xxct423x3zs3840";
	final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;

	File sdCard = Environment.getExternalStorageDirectory();
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	DropboxAPI<AndroidAuthSession> mDBApi;
	NotificationManager mNM;
	ManagerDB manager;
	String pathDir="";
	
	
	
	public Sincronizar() {
		super("Sincronizar");
		
	}

	
	@Override
	public void onCreate() {		
		super.onCreate();
		         mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);      
						showNotification("Cargando", (int) 100,(int) 0, new File(""));
				AndroidAuthSession session = buildSession();
				mDBApi = new DropboxAPI<AndroidAuthSession>(session);
				manager = new ManagerDB(this);
				
		
	}
	
	
	
	@Override
	protected void onHandleIntent(Intent intent) {
		
		inicio(manager.getImagenToSincronizar());
		
	}

		
	
	public void inicio(Imagen img) {
		if (img != null) {
			
			if (uploadfile(img.getUrl(), img.getAplicacion().getCliente().getCarpetaImagenes()+ img.getAplicacion().getPrevio().getReferencia()+"/"
					+ img.getNombre() + ".jpg")) {
				manager.updateImagenEstado(img.getIdImagen());
				pathDir=new File(img.getUrl()).getParentFile().getAbsolutePath();
				Imagen aux = manager.getImagenToSincronizar();
				inicio(aux);

			} else {
				mNM.cancel(R.string.hello_world);
				//stopForeground(true);
				Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
				v.vibrate(500);
				showNotificationError("Error!...Reintentar Envio!");
				stopSelf();
			}
			
		} else {
			mNM.cancel(R.string.hello_world);
			//stopForeground(false);
			deleteAll();
			stopSelf();
		}

	}
	
	
		
	public boolean uploadfile(final String urlInput, String urlOutput) {
		
		final File file = new File(urlInput);
		showNotification("Cargando", (int) 100,(int) 0, file);
		try {
			FileInputStream inputStream = new FileInputStream(file);
          
			Entry mRequest = mDBApi.putFileOverwrite(urlOutput, inputStream,
					file.length(),  new ProgressListener() {
						@Override
						public long progressInterval() {
							return 500;
						}

						@Override
						public void onProgress(long bytes, long total) {
							
							showNotification("Cargando", (int) total,	(int) bytes, file);
							//Toast.makeText(ServicioUpdatePicture.this, bytes+"", Toast.LENGTH_LONG).show();

						}
					});
			inputStream.close();
			
			if (mRequest != null) {                
                
				return true;
			}

		} catch (DropboxException e) {
			// TODO Auto-generated catch block
			Toast.makeText(Sincronizar.this, e.getMessage(), Toast.LENGTH_LONG).show();
			return false;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Toast.makeText(Sincronizar.this, e.getMessage(), Toast.LENGTH_LONG).show();
			return false;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Toast.makeText(Sincronizar.this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		
		return false;
	}

	private String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}

	private AndroidAuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
		AndroidAuthSession session;

		String[] stored = getKeys();
		if (stored != null) {
			com.dropbox.client2.session.AccessTokenPair accessToken = new com.dropbox.client2.session.AccessTokenPair(
					stored[0], stored[1]);
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE,
					accessToken);
		} else {
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
		}

		return session;
	}

	


	private void showNotification(String Cadena, int max, int pro, File file) {
		CharSequence text = Cadena;

		Notification notification = new Notification(R.drawable.ic_launcher,text,1);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MainActivity.class), 0);
		notification.setLatestEventInfo(this, "Servicio Rastreo", text,
				contentIntent);
		//notification.flags = Notification.FLAG_FOREGROUND_SERVICE;

		RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.notificacion);
		contentView.setProgressBar(R.id.progressBar1, max, pro, false);

		contentView.setImageViewResource(R.id.img, R.drawable.folder_upload);
		int percent = (int) (100.0 * (double) pro / max + 0.5);

		contentView.setTextViewText(R.id.textView1,
				"Uploading..... " + file.getName() + " (" + percent + "%)");
		notification.contentView = contentView;
		mNM.notify(R.string.hello_world, notification);
		
		//startForeground(1337,notification);
		
		
		

	}
	
	private void showNotificationError(String Cadena) {
		CharSequence text = Cadena;

		Notification notification = new Notification(R.drawable.error5,
				text, System.currentTimeMillis());
		
	
		PendingIntent contentIntent = PendingIntent.getService(this, 0,
				new Intent(this, Servico2UpdatePictures.class), 0);
		notification.setLatestEventInfo(this, "Servicio Rastreo", text,
				contentIntent);
		notification.flags = Notification.FLAG_ONGOING_EVENT;
		
		mNM.notify(R.string.hello_world, notification);
		//startForeground(R.string.hello_world, notification);
	
	}
	
	
	public void deleteAll(){
		try {
			manager.insertarRespuestas("http://192.168.1.74:8080/codeigniter_2.1.3/index.php/webservice/Webservice/insertRespuestas", manager.getAllRespuestasToJSon());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File dir= new File(pathDir);
		if(manager.daleteAll()){
			if (dir.isDirectory()) {
		        String[] children = dir.list();
		        for (int i = 0; i < children.length; i++) {
		            new File(dir, children[i]).delete();
		        }
		    }		    
		}     
		
	}



}

